package com.bst.bsj.biz.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.bst.bsj.biz.HttpService;
import com.bst.bsj.common.pojo.HttpParams;
import com.bst.bsj.spring.util.ConfigUtil;
import com.homewaimai.common.lang.Result;
import com.homewaimai.common.lang.ResultSupport;
import com.homewaimai.common.lang.StringUtil;

/**
 * 云片短信服务
 * 
 * @author Administrator
 */
@Service("smsApi")
public class YunPianSmsApiImpl extends AbsSmsApiImpl {

    /**
     * 短信http接口的java代码调用示例 基于Apache HttpClient 4.3
     *
     * @author songchao
     * @since 2015-04-03
     */

    // 查账户信息的http地址
    private static String GET_USER_INFO = "/v1/user/get.json";

    // 智能匹配模版发送接口的http地址
    private static String SEND_SMS      = "/v1/sms/send.json";

    // 模板发送接口的http地址
    private static String TPL_SEND_SMS  = "/v1/sms/tpl_send.json";

    // 发送语音验证码接口的http地址
    private static String SEND_VOICE    = "/v1/voice/send.json";

    @Autowired
    private HttpService   httpService;

    @PostConstruct
    private void init() {
        SERVER_ADDRESS = ConfigUtil.getProperties().getProperty("sms.server_address");
        SERVER_PORT = ConfigUtil.getProperties().getProperty("sms.server_port");
    }

    /**
     * 通过模板发送短信(不推荐)
     *
     * @param apikey apikey
     * @param tpl_id 　模板id
     * @param tpl_value 　模板变量值
     * @param mobile 　接受的手机号
     * @return json格式字符串
     * @throws IOException
     */
    @Override
    public Result sendSmsWithTemplate(String templateId, String appId, String to, String... strs) throws Exception {
        String tplValue = createTemplateValue(strs);
        String url = createUrl(SERVER_ADDRESS, SERVER_PORT, TPL_SEND_SMS);
        Map<String, String> paramsMap = new HashMap();
        paramsMap.put("apikey", appId);
        paramsMap.put("tpl_id", templateId);
        paramsMap.put("tpl_value", tplValue);
        paramsMap.put("mobile", to);

        Result result = baseSendRequest(url, paramsMap);
        return dealResult(result);

    }

    private Result sendSmsWithTemplateResult(String templateId, String appId, String to, String... strs)
                                                                                                        throws Exception {
        String tplValue = createTemplateValue(strs);
        String url = createUrl(SERVER_ADDRESS, SERVER_PORT, TPL_SEND_SMS);
        Map<String, String> paramsMap = new HashMap();
        paramsMap.put("apikey", appId);
        paramsMap.put("tpl_id", templateId);
        paramsMap.put("tpl_value", tplValue);
        paramsMap.put("mobile", to);
        Result result = baseSendRequest(url, paramsMap);
        return result;

    }

    private String createTemplateValue(String[] strs) {
        if (strs == null) return "";
        int len = strs.length;
        if (len == 0) return "";
        String str = "";
        if (len % 2 == 0) {
            for (int i = 0; i < len; i++) {
                str += "#" + strs[i] + "#=" + strs[++i] + "&";
            }
            str = str.substring(0, str.length() - 1);
            return str;
        } else {
            return null;
        }

    }

    private Result baseSendRequest(String url, Map<String, String> paramsMap) {
        List<HttpParams> list = new ArrayList();
        for (Map.Entry<String, String> param : paramsMap.entrySet()) {
            HttpParams pair = new HttpParams();
            pair.setKey(param.getKey());
            pair.setValue(param.getValue());
            list.add(pair);
        }
        return httpService.httpPost(url, list);
    }

    private String createUrl(String serverAddress, String serverPort, String partUrl) {
        if (StringUtil.isBlank(serverAddress)) {
            return null;
        }
        return "http://" + getStringBuffer().append(partUrl).toString();
    }

    /**
     * 通过模板发送短信(不推荐)
     *
     * @param apikey apikey
     * @param tpl_id 　模板id
     * @param tpl_value 　模板变量值
     * @param mobile 　接受的手机号
     * @return json格式字符串
     * @throws IOException
     */
    public Result sendSmsWithTemplate(String templateId, String appId, String to, String code) throws Exception {

        // 返回发送短信的响应体
        return sendSmsWithTemplate(templateId, appId, to, "code", code);
    }

    public Result sendSmsWithTemplate(String to, String code) throws Exception {
        String appId = ConfigUtil.getProperties().getProperty("sms.app_id");
        String templateId = ConfigUtil.getProperties().getProperty("sms.template_id");
        // 返回发送短信的响应体
        return sendSmsWithTemplate(templateId, appId, to, "code", code);
    }

    public Result sendSms(String to, String code) {
        try {
            return sendSmsWithTemplate(to, code);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResultSupport(false);
    }
    
    public Result sendSms(String to, Integer templateId, String name, String telphone) {
      try {
        String appId = ConfigUtil.getProperties().getProperty("sms.app_id");
        // 返回发送短信的响应体
        return sendSmsWithTemplate(templateId.toString(), appId, to, "name", name, "telphone", telphone);
      } catch (Exception e) {
          e.printStackTrace();
      }
      return new ResultSupport(false);
  }


    /**
     * 智能匹配模版接口发短信
     *
     * @param apikey apikey
     * @param text 　短信内容
     * @param mobile 　接受的手机号
     * @return json格式字符串
     * @throws IOException
     */
    @Override
    public Result sendSms(String appId, String to, String body, String msgType) throws Exception {
        String url = createUrl(SERVER_ADDRESS, SERVER_PORT, SEND_SMS);
        Map<String, String> paramsMap = new HashMap();
        paramsMap.put("apikey", appId);
        paramsMap.put("text", body);
        paramsMap.put("mobile", to);
        Result result = baseSendRequest(url, paramsMap);
        // 返回发送短信的响应体
        return dealResult(result);
    }

    @Override
    public Result sendVoiceVerify(String appId, String verifyCode, String to) throws Exception {

        String url = createUrl(SERVER_ADDRESS, SERVER_PORT, SEND_VOICE);
        Map<String, String> paramsMap = new HashMap();
        paramsMap.put("apikey", appId);
        paramsMap.put("mobile", to);
        paramsMap.put("code", verifyCode);
        Result result = baseSendRequest(url, paramsMap);
        String content = (String) result.getModel("content");

        // 返回发送短信的响应体
        return dealResult(result);

    }

    private Result dealResult(Result result) {
        if (result.isSuccess()) {
            String content = (String) result.getModel("content");
            // 成功：{"code":2,"msg":"请求参数格式错误","detail":"参数 tpl_value 格式不正确，tpl_value模板值中键值必须成对出现"}
            // 失败：{"code":0,"msg":"OK","result":{"count":1,"fee":1,"sid":3383390762}}
            JSONObject jsob = JSONObject.parseObject(content);
            String code = jsob.getString("code");
            if ("0".equals(code)) {
                // 成功
                String sid = "";
                try {
                    sid = jsob.getJSONObject("result").getString("sid");
                } catch (Exception e) {

                }
                result.setSuccess(true);
                result.setDefaultModel("data", sid);
            } else {
                // 失败
                String msg = "";
                if (jsob.containsKey("msg")) {
                    msg += jsob.getString("msg");
                }
                if (jsob.containsKey("detail")) {
                    msg += ":" + jsob.getString("detail");
                }
                result.setSuccess(false);
                result.setDefaultModel("data", msg);
            }

        }
        return result;

    }

}
